// config/config.go
package config

import (
	"encoding/json"
	"errors"
	"io/ioutil"
	"log"
	"os"
	"time"
)

// Config 应用配置结构
type Config struct {
	AppName    string         `json:"app_name"`
	AppEnv     string         `json:"app_env"`
	Port       string         `json:"port"`
	JWTSecret  string         `json:"jwt_secret"`
	JWTIssuer  string         `json:"jwt_issuer"`
	JWTExpire  time.Duration  `json:"jwt_expire"`
	Database   DatabaseConfig `json:"database"`
	LogLevel   string         `json:"log_level"`
	UploadPath string         `json:"upload_path"`
}

// DatabaseConfig 数据库配置
type DatabaseConfig struct {
	Driver   string `json:"driver"`
	Host     string `json:"host"`
	Port     string `json:"port"`
	Username string `json:"username"`
	Password string `json:"password"`
	Name     string `json:"name"`
	Charset  string `json:"charset"`
}

var instance *Config

// GetConfig 获取配置实例
func GetConfig() *Config {
	if instance == nil {
		instance = &Config{}
		if err := instance.Load(); err != nil {
			log.Fatalf("加载配置失败: %v", err)
		}
	}
	return instance
}

// Load 从文件加载配置
func (c *Config) Load() error {
	// 优先从环境变量获取配置文件路径
	configPath := os.Getenv("CONFIG_PATH")
	if configPath == "" {
		configPath = "config/config.json" // 默认配置文件路径
	}

	// 读取配置文件
	data, err := ioutil.ReadFile(configPath)
	if err != nil {
		return err
	}

	// 解析JSON配置
	if err := json.Unmarshal(data, c); err != nil {
		return err
	}

	// 应用环境变量覆盖配置
	c.overrideWithEnvVars()

	// 验证配置
	if err := c.validate(); err != nil {
		return err
	}

	return nil
}

// overrideWithEnvVars 使用环境变量覆盖配置
func (c *Config) overrideWithEnvVars() {
	if env := os.Getenv("APP_ENV"); env != "" {
		c.AppEnv = env
	}

	if port := os.Getenv("PORT"); port != "" {
		c.Port = port
	}

	if secret := os.Getenv("JWT_SECRET"); secret != "" {
		c.JWTSecret = secret
	}

	if dbHost := os.Getenv("DB_HOST"); dbHost != "" {
		c.Database.Host = dbHost
	}

	if dbPort := os.Getenv("DB_PORT"); dbPort != "" {
		c.Database.Port = dbPort
	}

	if dbUser := os.Getenv("DB_USER"); dbUser != "" {
		c.Database.Username = dbUser
	}

	if dbPass := os.Getenv("DB_PASS"); dbPass != "" {
		c.Database.Password = dbPass
	}

	if dbName := os.Getenv("DB_NAME"); dbName != "" {
		c.Database.Name = dbName
	}
}

// validate 验证配置
func (c *Config) validate() error {
	if c.Port == "" {
		c.Port = "8080" // 默认端口
	}

	if c.JWTSecret == "" {
		return ErrMissingJWTSecret
	}

	if c.Database.Host == "" {
		c.Database.Host = "localhost"
	}

	if c.Database.Port == "" {
		c.Database.Port = "3306"
	}

	if c.JWTExpire == 0 {
		c.JWTExpire = 24 // 默认24小时
	}

	return nil
}

// Error definitions
var (
	ErrMissingJWTSecret = errors.New("缺少JWT密钥配置")
)
